package com.hzmg.route.akka.route.sample1;

import akka.actor.typed.*;
import akka.actor.typed.javadsl.Behaviors;
import akka.actor.typed.javadsl.GroupRouter;
import akka.actor.typed.javadsl.Routers;
import akka.actor.typed.receptionist.Receptionist;
import akka.actor.typed.receptionist.ServiceKey;

public class GroupRoute {
    static Behavior<Void> showGroupRouting() {
        ServiceKey<Worker.Command> serviceKey = ServiceKey.create(Worker.Command.class, "log-worker");

        return
                Behaviors.setup(
                        context -> {
                            // 有可能出现在其他地方， 如果在本地创建，也可以使用池创建
                            ActorRef<Worker.Command> worker = context.spawn(Worker.create(), "worker");
                            context.getSystem().receptionist().tell(Receptionist.register(serviceKey, worker));

                            GroupRouter<Worker.Command> group = Routers.group(serviceKey);
                            ActorRef<Worker.Command> router = context.spawn(group, "worker-group");

                            for (int i = 0; i < 10; i++) {
                                router.tell(new Worker.DoLog("msg " + i));
                            }

                            return Behaviors.empty();

                        });
    }

    public static void main(String[] args) {
        ActorSystem<Void> system =
                ActorSystem.create(
                        Behaviors.setup(
                                context -> {
                                    context.spawn(showGroupRouting(), "pool-router-setup");
                                    return Behaviors.empty();
                                }),
                        "RouterTest");

    }

}
